﻿using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Services;

namespace CMS.Web.Manage.Ashx {
	/// <summary>
	/// xhEditor HTML 编辑器的文件上传功能接收类
	/// </summary>
	[WebService(Namespace = "http://tempuri.org/")]
	[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
	public class EditorUpload : IHttpHandler {
		public void ProcessRequest(HttpContext context) {
			context.Response.ContentType = "text/plain";
			context.Response.Charset = "UTF-8";

			#region fields

			// 上传大小限制, 默认2M
			int max_length = 1024 * 1024 * 2;

			// 上传扩展名限制
			string allow_extension = "|txt|rar|zip|jpg|jpeg|gif|png|swf|wmv|avi|wma|mp3|mid|";

			// 上传文件保存路径, 结尾不要带"/"
			string upload_dir = "images/upload";

			// 立即上传模式 (不用等上传后再点确定按钮)
			string immediate = "1";

			// 返回上传参数的格式,  1:只返回url, 2:返回参数数组
			int msg_type = 1;

			string disposition = context.Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];

			string err = "";
			string msg = "";

			string fileName;
			byte[] fileBytes;

			#endregion

			if (disposition != null) {
				// HTML5 方式上传
				fileName = context.Server.UrlDecode(Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value); // 读取原始文件名
				fileBytes = context.Request.BinaryRead(context.Request.TotalBytes);
			}
			else {
				HttpPostedFile postedFile = context.Request.Files.Get("filedata");

				fileName = postedFile.FileName;
				fileBytes = new byte[postedFile.ContentLength];
				postedFile.InputStream.Read(fileBytes, 0, fileBytes.Length);
			}

			#region 对接收到的文件进行检测

			if (fileBytes.Length == 0) {
				err = "无数据提交";
			}
			else if (fileBytes.Length > max_length) {
				err = string.Format("文件大小超过 {0} 字节", max_length);
			}
			else {
				string extension = fileName.Substring(fileName.LastIndexOf('.') + 1);

				if (allow_extension.IndexOf("|" + extension + "|") < 0) {
					err = "上传文件扩展名必需为: " + allow_extension;
				}
			}

			#endregion

			if (err != "") {
				context.Response.Write("{'err':'" + JsonString(err) + "','msg':''}");
				return;
			}

			#region 保存文件

			string dir = "/" + upload_dir + "/" + DateTime.Now.ToString("yyyyMM");

			if (!Directory.Exists(context.Server.MapPath(dir)))
				Directory.CreateDirectory(context.Server.MapPath(dir));

			string url = dir + "/" + DateTime.Now.ToString("yyyyMMddhhmmssff") + fileName.Substring(fileName.LastIndexOf('.'));

			File.WriteAllBytes(context.Server.MapPath(url), fileBytes);

			#endregion

			if (immediate == "1")
				url = "!" + url;

			url = JsonString(url);

			if (msg_type == 1)
				msg = "'" + url + "'";
			else
				msg = string.Format("{{'url':'{0}','localname':'{1}','id':'1'}}", url, JsonString(fileName));

			context.Response.Write(string.Format("{{'err':'{0}','msg':{1}}}", JsonString(err), msg));
		}

		private string JsonString(string str) {
			str = str.Replace("\\", "\\\\");
			str = str.Replace("/", "\\/");
			str = str.Replace("'", "\\'");

			return str;
		}

		public bool IsReusable {
			get {
				return false;
			}
		}
	}
}